import http from 'http'
// import C from './config'
import L from './localStore'

let remote = ''

const fs = require('fs')
const path = require('path')

// const pro = require("child_process");
let userPath = remote ? remote.getGlobal('userDataPath') : ''
const HELPER = {

  httpPost: (options, data) => {
    return new Promise(function (resolve, reject) {
      try {
        let postData = JSON.stringify(data)
        let req = http.request(options, function (res) {
          res.setEncoding('utf-8')
          let data = ''
          res.on('data', function (chun) {
            data += chun
          })
          res.on('end', function () {
            if (Number(res.statusCode) === 200) {
              resolve(data)
            } else {
              reject(new Error(data))
            }
          })
        })
        req.on('error', function (err) {
          reject(err)
        })
        if (postData) req.write(postData)
        // req.write(data);
        req.end()
      } catch (e) {
        reject(e)
      }
    })
  },

  // 判断是否在线，连接本地还是ip
  isOnline: () => {
    return new Promise(async (resolve, reject) => {
      try {
        let config = L.LocalStore.getSetupInfo()
        const IS_ONLNE = {
          host: 'localhost',
          port: 61589,
          path: '/Witness_WCF/WitnessImp/WitnessHost/IsOnline',
          method: 'POST'
        }
        try {
          IS_ONLNE.host = config.serverIp
          await send(IS_ONLNE)
        } catch (error) {
          IS_ONLNE.host = 'localhost'
          await send(IS_ONLNE)
        }
        resolve({ host: IS_ONLNE.host })
      } catch (e) {
        reject(e)
      }
    })
  },

  // 写文件
  write: function (filename, data) {
    return new Promise((resolve, reject) => {
      try {
        let p = path.join(userPath, 'caselog')
        if (!fs.existsSync(p)) {
          fs.mkdirSync(p)
        }
        fs.appendFileSync(path.join(p, filename), data)
        resolve()
      } catch (e) {
        return reject(e)
      }
    })
  }
}

function send (posthost) {
  return new Promise((resolve, reject) => {
    let p = Promise.race([HELPER.httpPost(posthost, {})])

    p.then((result) => {
      result = JSON.parse(result)
      if (result.errmsg === '') {
        return resolve()
      }
    }).catch((e) => {
      return reject(e)
    })
  })
}

export default {
  HELPER
}
